package com.javandad.app.server.servlet.http;

import java.io.InputStream;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.server.entity.Fodo;
import com.javandad.app.shared.entity.User;

@SuppressWarnings("serial")
public class ImageUploader extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse res) {
		// Get the image representation
		try {

			HttpSession session = req.getSession();
            User user= (User)session.getAttribute("user");
			
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(req);;
            
			FileItemStream imageItem = iter.next();
			InputStream imageStream = (InputStream) imageItem.openStream();

			// construct our entity objects
			Blob imageBlob = new Blob(IOUtils.toByteArray(imageStream));
            
			Fodo fodo = new Fodo(imageItem.getName(),null ,user.getUsername(), imageBlob, null );

			// persist image
			PersistenceManager pm = PMFSingleton.getPM();
			pm.makePersistent(fodo);
			pm.close();

			// respond to query
			res.setContentType("text/plain");
			ServletOutputStream out = res.getOutputStream();
			out.write(fodo.getId().toString().getBytes());
			
			
	
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
